﻿using Core.FrameWork.Commons;
using Core.FrameWork.Commons.App;
using Core.FrameWork.Commons.App.HttpContextUser;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Loging.Model;
using Core.FrameWork.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Core.Web.Api.Middleware
{
    /// <summary>
    /// 记录用户行为中间件
    /// </summary>
    public class RecordHandlerAccessLogsMilddleware
    {
        private readonly RequestDelegate _next;
        private readonly IHttpContextUser _user;

        private readonly Stopwatch _stopwatch;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="next"></param>
        /// <param name="user"></param>
        public RecordHandlerAccessLogsMilddleware(RequestDelegate next, IHttpContextUser user)
        {
            _next = next;
            _user = user;
            _stopwatch = new Stopwatch();
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (!APIConfig.ApiSetting.RecordUsersLogs)//是否开启记录用户行为操作
                await _next(context);
            else
            {
                if (!_user.IsAuthenticated())//是否已授权
                    await _next(context);
                else
                {
                    var api = context.Request.Path;//路径

                    if (string.IsNullOrEmpty(api))//路径是否为空
                        await _next(context);
                    if (!api.ToString().TrimEnd('/').ToLower().Contains("api"))// 过滤，只有接口
                        await _next(context);

                    _stopwatch.Restart();
                    var userAccessModel = new UserAccessModel();

                    HttpRequest request = context.Request;

                    userAccessModel.API = api;
                    userAccessModel.User = _user.GetUserInfo().Name;
                    userAccessModel.IP = IPLogHandlerMilddleware.GetClientIp(context);
                    userAccessModel.BeginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    userAccessModel.RequestMethod = request.Method;
                    userAccessModel.Agent = request.Headers["User-Agent"].ToString();


                    // 获取请求body内容
                    if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put"))
                    {
                        // 启用倒带功能，就可以让 Request.Body 可以再次读取
                        request.EnableBuffering();

                        Stream stream = request.Body;
                        byte[] buffer = new byte[request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        userAccessModel.RequestData = Encoding.UTF8.GetString(buffer);

                        request.Body.Position = 0;
                    }
                    else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete"))
                    {
                        userAccessModel.RequestData = HttpUtility.UrlDecode(request.QueryString.ToString(), Encoding.UTF8);
                    }

                    // 获取Response.Body内容
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                    {
                        context.Response.Body = responseBody;

                        await _next(context);

                        var responseBodyData = await GetResponse(context.Response);

                        await responseBody.CopyToAsync(originalBodyStream);
                    }


                    var dt = DateTime.Now;

                    // 响应完成记录时间和存入日志
                    context.Response.OnCompleted(() =>
                    {
                        _stopwatch.Stop();

                        userAccessModel.OPTime = _stopwatch.ElapsedMilliseconds + "ms";

                        // 自定义log输出
                        var requestInfo = System.Text.Json.JsonSerializer.Serialize(userAccessModel);
                        Parallel.For(0, 1, e =>
                        {
                            LogLockHelper.OutSql2Log("RecordAccessLogs", "RecordAccessLogs" + dt.ToString("yyyy-MM-dd"), new string[] { requestInfo + "," }, false);
                        });

                        return Task.CompletedTask;
                    });
                    await _next(context);
                }
            }
        }
        /// <summary>
        /// 获取响应内容
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public async Task<string> GetResponse(HttpResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);
            var text = await new StreamReader(response.Body).ReadToEndAsync();
            response.Body.Seek(0, SeekOrigin.Begin);
            return text;
        }

    }

}
